﻿using Furion;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MyProject.Util;
using MyProject.WebApi.Handlers;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyProject.WebApi
{

    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCorsAccessor();

            // JWT 验证
            services.AddJwt<JwtHandler>(enableGlobalAuthorize: true);

            services.AddControllers()
                    .AddNewtonsoftJson(options =>
                    {
                        // 返回数据首字母不小写，CamelCasePropertyNamesContractResolver是小写
                        options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                    })
                    .AddInjectWithUnifyResult()
                    .AddFriendlyException() // 注册友好异常服务
                    .AddUnifyResult<ExResultProvider>();

            // 注册拦截器
            services.AddScoped<AuthorizeFilterAttribute>();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCorsAccessor();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });


            GlobalContext.LogWhenStart(env);
            GlobalContext.HostingEnvironment = env;
        }
    }
}
